package com.guangwei.lockscreenforelder.lockscreen

import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.guangwei.lockscreenforelder.R
import com.guangwei.lockscreenforelder.util.Validator

class LauncherHomeActivity : AppCompatActivity() {
    private var mPackageName: String? = null
    private var mClassName: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        println("LauncherHOmeActivity: onCreate")
        setContentView(R.layout.activity_launcher_home)
    }

    override fun onResume() {
        super.onResume()

        println("LauncherHOmeActivity: onResume")
        Log.i("LockScreen", "LauncherHOmeActivity: onResume")
        LockScreenService.startLockScreenService(this)

        getLauncherPackageName(this)

        if (!LockScreenActivity.isLocked) {
            if (Validator.isEffective(mPackageName) && Validator.isEffective(mClassName)) {
                val systemIntent = Intent()
                systemIntent.component = ComponentName(mPackageName.toString(), mClassName.toString())
                startActivity(systemIntent)
            }
        }

        moveTaskToBack(false)
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
    }

    /**
     * get the system launcher package name and class name,we use system launcher as default<br></br>
     * also we can let user to choose a launcher from system laucher and our custom launchers,"BaiDu" lock screen app and "Go" lock screen app just do this.<br></br>
     *
     * @param context
     */
    @SuppressLint("WrongConstant")
    private fun getLauncherPackageName(context: Context) {
        val intent = Intent(Intent.ACTION_MAIN)
        intent.addCategory(Intent.CATEGORY_HOME)
        val resInfoList = context.packageManager.queryIntentActivities(intent, PackageManager.GET_ACTIVITIES)
        if (resInfoList != null) {
            var resInfo: ResolveInfo
            for (i in resInfoList.indices) {
                resInfo = resInfoList[i]
                if (resInfo.activityInfo.applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM > 0) {
                    mPackageName = resInfo.activityInfo.packageName
                    mClassName = resInfo.activityInfo.name

                    break
                }
            }
        }
    }
}
